package duyd.hibernate.training.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.junit.Test;

import duyd.hibernate.training.domain.Event;

public class HibernateEnvers extends HibernateJPA {

    @Test
    public void test() {
        // Create 2 Events
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.persist(new Event("First Event", new Date()));
        entityManager.persist(new Event("Second Event", new Date()));
        entityManager.getTransaction().commit();
        entityManager.close();

        // Retrieve 2 Events
        entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        List<Event> result = entityManager.createQuery("from Event", Event.class).getResultList();
        for (Event event : result) {
            System.out.println("Event " + event.getId() + ": " + event.getTitle() + " " + event.getDate());
        }

        // Update the Event 2
        Event event = entityManager.find(Event.class, 2L);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        event.setDate(new Date());
        event.setTitle(event.getTitle() + " (rescheduled)");
        entityManager.getTransaction().commit();
        entityManager.close();

        // Check revisions of Event 2
        entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        AuditReader auditReader = AuditReaderFactory.get(entityManager);
        Event firstRevision = auditReader.find(Event.class, 2L, 1);
        Event secondRevision = auditReader.find(Event.class, 2L, 2);
        assertEquals(firstRevision.getId(), secondRevision.getId());
        assertFalse(firstRevision.getTitle().equals(secondRevision.getTitle()));
        assertFalse(firstRevision.getDate().equals(secondRevision.getDate()));
        entityManager.getTransaction().commit();
        entityManager.close();
    }

}
